/** @jsxImportSource @emotion/react */
import { css} from "@emotion/react";
import * as React from "react";
import {
    List, ListItem, Button, useTheme, Skeleton, useToast, Text, VerticalMenu, DdMenuItem, Itext, ListFlexRow, useMMenuBarOcup, Stack, StackItem, Link, LineColumn,
} from "customize-easy-ui-component";
import {useContext, useRef} from "react";
import { useInView } from 'react-intersection-observer'
import RoutingContext from "../routing/RoutingContext";
import {usePaginationFragment, } from "react-relay/hooks";
import {HeadlinesList$key} from "./__generated__/HeadlinesList.graphql";
import {SearchTitle} from "../comp/base";
const graphql = require("babel-plugin-relay/macro");


interface DeviceListProps {
    eqps: HeadlinesList$key;
    filter: any   //传递
}
//还要把：爬取链接说明书.xlsx 手动上传到minIO服务器去。
export const PipingUnitEsListParent: React.FunctionComponent<
    DeviceListProps
> = props => {
    const theme = useTheme();
    const [query, setQuery] = React.useState<string>('');        //安排在共同祖先的组件添加状态变量操作函数。
    const [index, setIndex] = React.useState(0);
    const {history } = useContext(RoutingContext);
    const {barHeight } = useMMenuBarOcup(history.routeData?.isExact);
    console.log("共同祖先简易框query=",query, "上一级给的history=",history);
    return (
        <React.Fragment>
            <Stack
                navStyle={css({ position: 'sticky',  top: 0,})}
                style={{
                    overflow: 'unset'
                }}
                index={index}
                navHeight={60}
                onIndexChange={i => setIndex(i)}
                items={[
                    {
                        title: (
                            <SearchTitle >
                              <div><Text variant="h4" css={{ textAlign: 'center' }}>特检头条</Text>
                                  <div css={{display:'flex',justifyContent:"space-around"}}>
                                      <Text >业界资讯等</Text>
                                      <Text >下载<Link href={process.env.REACT_APP_OSS_ENDP+"ywmast/爬取链接说明书.xlsx"}>已挖掘资源集说明</Link></Text>
                                  </div>
                              </div>
                            </SearchTitle>
                        ),
                        content: (
                            <StackItem className="ItemConte"
                                       css={{
                                           marginBottom: `${barHeight}`,
                                       }}
                                       style={{ position: undefined, boxShadow:undefined }}
                            >
                                <div className="DlistInnerF1"
                                     css={{overflowY: "auto", height: "100%",}}
                                >

                                    <HeadlinesList eqps={props.eqps} filter={props.filter} query={query}/>
                                </div>
                            </StackItem>
                        )
                    },
                ]}
            />
        </React.Fragment>
    );
};


interface DeviceListInnerProps {
    eqps: HeadlinesList$key;
    //常规过滤器设置参数，通过路由器和sessionStorage存储的。
    filter: any   //用props参数看看
    //特殊的简易搜索框输入的参数做过滤的，作用范围较为短暂,不通过路由器sessionStorage，只会在当前mount组件的状态变量进行传递的。
    query: string     //还是把简易搜索输入框的内容传递下去
}
export const HeadlinesList: React.FunctionComponent<
  DeviceListInnerProps
> = (props: DeviceListInnerProps) => {
  const theme = useTheme();
  const { history } = useContext(RoutingContext);
    const toast = useToast();
  const { data, refetch , loadNext,hasNext,isLoadingNext} = usePaginationFragment(
      graphql`
        fragment HeadlinesList on Query
        @refetchable(queryName: "HeadlinesListRefetchQuery") {
            searchNewsEs(where: $where,after:$after,first:$first,orderBy:$orderBy,asc:$asc)
          @connection(key: "Query__searchNewsEs") {
              edges {
                  __id
                  node {
                      id url title pdate tags chn site crDate
                  }
              }
          }
        }
      `,
      props.eqps,
  );
  const {searchNewsEs }=data;
    const devicesFind=searchNewsEs?.edges;
    const queryRef =useRef('');       //初始化值必须和输入组件query的一样！否则底下queryChanged逻辑变导致多次触发refetch();
  const refLsize = React.useRef(0);
  const [refMore, acrossMore] = useInView({threshold: 0});


    React.useEffect(() => {
        //【避免重复】触发refetch(),这里的参数构造结果应该和路由器入口构造结果保证一致。否则就会发生两次查询。DeviceMainQuery有可能不止于一个DeviceListInnerRefetchQuery查询组件，可能多个组件一次性放在一个graphQL发送包一起发给后端的。
        let filtercomp={where: {cod: props.query===""?undefined:props.query, ...props.filter.where},
            offset:0,
            first: 5,
            asc: props.filter.asc
        };
        let queryChanged= false;
        if(queryRef.current !== props.query){
            queryRef.current = props.query as any;
            queryChanged= true;
        }
        //使用useEffect的缺陷：若cod="",无法切换回去，必须知道cod前面一次赋值来对比。
        if(queryChanged || JSON.stringify(props.filter) !== JSON.stringify(filtercomp) ) {
            console.log("JY每次都要的发起更新@=",refetch,"filter=",filtercomp);
            refetch(filtercomp, {fetchPolicy: 'network-only'});      //尽量避免路由器myQuery: loadQuery(vars)里面有两个以上的查询，多个查询有各自的参数名字空间，需要独立分离参数，filter的多参数拆分独立。
        }
    }, [props.query, props.filter, refetch]);

    const {save, field, reurl, p1field, multi}= window.history.state?.state??{};      //通用伪对话框传递格式
    console.log("最近devicesFind队列长度=",devicesFind?.length,"filter=",props.filter);
    // const {enlarge, setEnlarge,setActivecas} =useContext(PanelEnlargeCtx);
  //控件<Stack 是堆叠式的，像导航条；适用同一个模板显示只需上级给下级参数调整的场景。根据上一叠页面选择触发状态relation给下一叠参数来控制下一级显示；更多嵌套很困难。
  return (
    <React.Fragment>
            <List className="DlistInner">
              {isLoadingNext && (
                <React.Fragment>
                  <ListItem
                    interactive={false}
                    contentBefore={
                      <Skeleton
                        css={{
                          width: "32px",
                          height: "32px",
                          borderRadius: "50%"
                        }}
                      />
                    }
                    primary={<Skeleton css={{ maxWidth: "160px" }} />}
                  />
                  <ListItem
                    interactive={false}
                    contentBefore={
                      <Skeleton
                        css={{
                          width: "32px",
                          height: "32px",
                          borderRadius: "50%"
                        }}
                      />
                    }
                    primary={<Skeleton css={{ maxWidth: "200px" }} />}
                  />
                </React.Fragment>
              )}

                <LineColumn column={3} >
                    {devicesFind?.map((hit,i) => {
                        const dev= hit?.node!;
                        return (
                            <ListFlexRow
                                key={dev?.id}
                                interactive={ true}
                                onPress={(e) => {
                                    e?.stopPropagation();
                                }}
                                contentAfter={
                                    <VerticalMenu>
                                        <DdMenuItem label="功能待续"
                                                    onClick={(e) => {
                                                    }}/>
                                    </VerticalMenu>
                                }
                            >
                                <Link
                                    href={ dev?.url || '/'}
                                    title="Creative Commons BY 3.0"
                                    target="_blank"
                                >
                                    <Text>{ dev.title || '*' }</Text>
                                </Link>
                                <Itext>{ `${dev.site || '?'}` }</Itext>
                                <Text>{ dev.pdate }</Text>
                            </ListFlexRow>
                        );
                    })}
                </LineColumn>

            </List>
              <div
                css={{
                  textAlign: "center",
                  marginBottom: theme.spaces.md,
                  marginTop: theme.spaces.md
                }}
              >
                { hasNext &&  (
                  <div>
                    <Button disabled={isLoadingNext}
                            onPress={async (e) => {
                                e?.stopPropagation();
                                await loadNext(10,{
                                    onComplete: (error) =>  {
                                        if(error){
                                            toast({
                                                title: "返回了",
                                                subtitle: ""+error,
                                                intent: "error"
                                            });
                                        }
                                    }
                                });
                            } }
                            >
                      按，拉扯获取更多......
                    </Button>
                  </div>
                )}
                {(refLsize.current===devicesFind?.length)  &&　<React.Fragment>
                      <span>嘿，没有更多了</span>
                  </React.Fragment>
                }
              </div>
              {/*<div  ref={refMore}  css={{height: "1px"}}> </div>*/}
    </React.Fragment>
  );
};
